<?php
/**
  * wechat php test
  */
function onError($severity, $message, $filepath, $line){
	$log = array(
			'severity'=>$severity,
			'message'=>$message,
			'filepath'=>$filepath,
			'line'=>$line,
	);
	$log = json_encode($log,JSON_UNESCAPED_UNICODE)."\n";
	$file = dirname(dirname(__DIR__)).'/app_hsd78wsx/logs/WxWebCbLog';
	file_put_contents($file, $log,FILE_APPEND);
}
set_error_handler('onError');



//define your token
define("TOKEN", "aliwe8zlwlewe89sfwafaefaf76afsdf");
define("ROOT",dirname(dirname(dirname(__FILE__))).'/');
define("LOG_PATH",ROOT.'data/wechatWebLog/');

/**
 * 协议:http/https
 */
define('PROTOCOL',(isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && $_SERVER['HTTP_X_CLIENT_SCHEME']=='https') ? 'https://' : 'http://' );
/**
 * 域名
*/
define('BASE_URL', PROTOCOL.(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'].'/' : 'health-api.yxlady.com/'  ));



$wechatObj = new wechatCallbackapiTest();
if ( isset($_GET["echostr"]) ) {
	$wechatObj->valid();
}else{
	$wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function log($msg){
        list($m,$t) = explode(' ',microtime());
        $file = LOG_PATH.date('Y_m_d__H_i_s_',$t).round($m*10000).'_'.mt_rand(0,9999);
        file_put_contents($file,$msg);
    }

    public function responseMsg()
    {
      	//extract post data
		if (!empty($GLOBALS["HTTP_RAW_POST_DATA"])){
			//get post data, May be due to the different environments
			$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
			
            $this->log($postStr);
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;//用户openID
                $toUsername = $postObj->ToUserName;//开发者微信号
                $time = time();
                if ( ! empty($postObj->MsgType) && $postObj->MsgType=='event'  ) {
                	if ( $postObj->Event == 'subscribe' ) { // "关注"事件
                		$picUrl = BASE_URL.'images/logo.png';
                		$url    = BASE_URL.'wx/main/index?#/tyy/own';
                		$tpl = "<xml>
									<ToUserName><![CDATA[$fromUsername]]></ToUserName>
									<FromUserName><![CDATA[$toUsername]]></FromUserName>
									<CreateTime>$time</CreateTime>
									<MsgType><![CDATA[news]]></MsgType>
									<ArticleCount>1</ArticleCount>
									<Articles>
										<item>
										<Title><![CDATA[欢迎关注伊秀女性网]]></Title> 
										<Description><![CDATA[回答问题赚收益,赶紧填写资料成为认证医生吧]]></Description>
										<PicUrl><![CDATA[$picUrl]]></PicUrl>
										<Url><![CDATA[$url]]></Url>
										</item>
									</Articles>
								</xml>";
                		echo $tpl;
                		exit();
                	}
                }else{
                    echo '';
                    exit;
                }
    //             $keyword = trim($postObj->Content);
                
    //             $textTpl = "<xml>
				// 			<ToUserName><![CDATA[%s]]></ToUserName>
				// 			<FromUserName><![CDATA[%s]]></FromUserName>
				// 			<CreateTime>%s</CreateTime>
				// 			<MsgType><![CDATA[%s]]></MsgType>
				// 			<Content><![CDATA[%s]]></Content>
				// 			<FuncFlag>0</FuncFlag>
				// 			</xml>";             
				// if(!empty( $keyword ))
    //             {
    //           		$msgType = "text";
    //             	$contentStr = "Welcome to wechat world!";
    //             	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //             	echo $resultStr;
    //             }else{
    //             	echo "Input something...";
    //             }

        }else {
        	echo "";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}





